import React, { lazy, Suspense } from "react";
import { withRouter, Redirect, Route, Switch } from "react-router-dom";

import MayLayout from "@/components/layout/MayLayout";

import Login from "@/pages/Login";
import Erro404 from "@/pages/Erro404";
const Home = lazy(() => import("@/pages/Home"));
const Goodsmanag = lazy(() => import("@/pages/Goodsmanage"));
const Banner = lazy(() => import("@/pages/Banner"));
const Member = lazy(() => import("@/pages/Member"));
const Redux = lazy(() => import("@/pages/redux"));

/**
 * 白名单 用来设定 未登录就可以访问的页面
 *
 */
const whiteList = ["/login", "/reg"];

/**
 * 路由列表 一个网页分为多个模块 每个模块会有几个到几十个页面，
 * 我们一般只需要判断该模块下的页面是否可以在登录前访问，
 *
 */
const routeList = [
  {
    path: "/login",
    component: Login,
  },
  {
    path: "/",
    component: Home,
  },
  {
    path: "/goodsmanage",
    component: Goodsmanag,
  },
  {
    path: "/member",
    component: Member,
  },
  {
    path: "/banner",
    component: Banner,
  },
  {
    path: "/redux",
    component: Redux,
  },
];

function isAuth(token) {
  return token;
}
function RouterGurd(props) {
  let pathname = props.location.pathname;
  let currPath = pathname.match(/\/(\w*)/)[0];
  // console.log(pathname, currPath);

  const isRoute = routeList.find((route) => {
    return route.path === currPath;
  });
  // console.log(isRoute);
  if (!isRoute) {
    return <Route component={Erro404} />;
  }
  const { path, component } = isRoute;
  if (isAuth(window.localStorage.getItem("token"))) {
    if (pathname === "/login") {
      return (
        <Suspense fallback={"loading..."}>
          <Redirect to="/" />
        </Suspense>
      );
    }
    return (
      <MayLayout>
        <Suspense fallback={"loading..."}>
          <Switch>
            <Route path={path} component={component} />
          </Switch>
        </Suspense>
      </MayLayout>
    );
  } else {
    if (whiteList.includes(path)) {
      return <Route path={path} component={component} />;
    }
    return <Redirect to={"/login?" + pathname} />;
  }
}

export default withRouter(RouterGurd);
